import { Injectable,HttpException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { CryptoUtil } from 'src/common/utils/crypto.util';
import { User } from 'src/entities/user.entity';
import { Repository } from 'typeorm';
import { UserRegisterDto } from 'src/dto/user/user-register.dto';


@Injectable()
export class UserService {
    async onModuleInit() {
        // if (await this.findOneByAccount('admin')) return;
        // // 初始化系统管理员
        // const admin = this.userRepository.create({
        //     account: 'admin',
        //     password: this.cryptoUtil.encryptPassword("admin"),
        //     username: "系统管理员",
        //     roles: "admin"
        // });
        // await this.userRepository.save(admin);
    }
    // 注入 一个操作数据表，一个加密密码
    constructor(
        @InjectRepository(User)
        private readonly userRepository: Repository<User>,
        private readonly cryptoUtil: CryptoUtil,
    ) { }

    /**
     * 通过登录账号查询用户
     *
     * @param username 登录账号
     */
    async findOneByAccount(username: string): Promise<User> {
        const user = await this.userRepository.findOne({
            where: {
                username
            }
        });
        return user
    }

    /**
  * 创建用户
  * @param user 
  */
    async register(user: UserRegisterDto): Promise<void> {
        const existing = await this.findOneByAccount(user.username);
        // 406 Not Acceptable
        if (existing) throw new HttpException("账户已经存在了", 406);
        user.password = this.cryptoUtil.encryptPassword(user.password);
        await this.userRepository.save(this.userRepository.create(user));
    }

    async findOne(username: string): Promise<User | undefined> {
        console.log("user service ts findone enter", username);
        const user = await this.userRepository.findOne({
            where: {
                username
            }
        });

        console.log("user service ts findone leave", user);
        return user;
    }
    async findAll(){
        console.log("user service ts findone enter",);
        const user = await this.userRepository.find({select: ['id', 'username', 'roles', /* 其他字段 */]});

        console.log("user service ts findone leave", user);
        return user;
    }
}
